package com.taotao.health.service.impl;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
@Service
public class ChatServiceImpl {

    // 远程调用

    private final String chatEndpoint = "https://api.deepseek.com/chat/completions";
    private final String apiKey = "sk-009071728ffd4fb5aadb202d2ca5df31";
    private final List<Map<String, String>> dataList = new ArrayList<>();
    public ChatServiceImpl() {
        // 初始化系统角色
        dataList.add(new HashMap<String, String>() {{
            put("role", "system");
            put("content", "1111");
        }});
        // 发送初始提示消息
       // sendSystemWelcome();
    }

//    private void sendSystemWelcome() {
//        dataList.add(new HashMap<String, String>() {{
//            put("role", "assistant");
//            put("content", "欢迎使用健康AI助手！有什么健康方面的问题需要帮助吗？");
//        }});
//    }

    public String chat(String txt) {
        // 检查是否连续发送用户消息
        if (!dataList.isEmpty()) {
            Map<String, String> lastMessage = dataList.get(dataList.size() - 1);
            if ("user".equals(lastMessage.get("role"))) {
                throw new IllegalStateException("无法添加连续的用户消息。请等待助手的回复");
            }
        }

        // 检查用户输入是否为空
        if (txt == null || txt.trim().isEmpty()) {
            return createResponse(200, "success", "输入不能为空，请输入您的问题").toJSONString();
        }
        // 检查特定的欢迎指令
//        if ("欢迎".equals(txt.trim())) {
//            return createResponse(200, "success", "欢迎使用健康AI助手！有什么健康方面的问题需要帮助吗？").toJSONString();
//        }


        // 添加用户消息
        dataList.add(new HashMap<String, String>() {{
            put("role", "user");
            put("content", txt);
        }});

        // 构造请求参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("model", "deepseek-chat");
        paramMap.put("messages", dataList);

        try {
            // 发送 HTTP 请求
            String body = HttpRequest.post(chatEndpoint)
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute()
                    .body();

            // 解析 API 响应
            JSONObject jsonObject = JSON.parseObject(body);
            if (jsonObject.containsKey("error")) {
                throw new IllegalStateException(jsonObject.getJSONObject("error").getString("message"));
            }

            // 提取 AI 回复并格式化
            JSONArray choices = jsonObject.getJSONArray("choices");
            JSONObject firstChoice = choices.getJSONObject(0);
            JSONObject message = firstChoice.getJSONObject("message");
            String res = message.getString("content");

            // 格式化返回结果
            JSONObject response = new JSONObject();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", res);

            // 将 AI 回复添加到对话历史
            dataList.add(new HashMap<String, String>() {{
                put("role", "assistant");
                put("content", res);
            }});

            //打印数据
            System.out.println(response);
            System.out.println(dataList);
            return response.toJSONString();

        } catch (Exception e) {
            // 错误处理
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("code", 500);
            errorResponse.put("message", "API 调用失败: " + e.getMessage());
            errorResponse.put("data", null);
            return errorResponse.toJSONString();
        }
    }

    private JSONObject createResponse(int code, String message, Object data) {
        JSONObject response = new JSONObject();
        response.put("code", code);
        response.put("message", message);
        response.put("data", data);
        return response;
    }

    /**
     * 流式聊天方法
     * @param txt 用户输入的文本
     * @param callback 处理流式响应的回调函数
     */
    public void streamChat(String txt, Consumer<String> callback) {
        // 检查是否连续发送用户消息
        if (!dataList.isEmpty()) {
            Map<String, String> lastMessage = dataList.get(dataList.size() - 1);
            if ("user".equals(lastMessage.get("role"))) {
                callback.accept("请等待上一条消息的回复完成");
                return;
            }
        }

        // 检查用户输入
        if (txt == null || txt.trim().isEmpty()) {
            callback.accept("输入不能为空，请输入您的问题");
            return;
        }

        // 检查特定的欢迎指令
        if ("欢迎".equals(txt.trim())) {
            callback.accept("欢迎使用健康AI助手！有什么健康方面的问题需要帮助吗？");
            return;
        }

        // 添加用户消息到历史记录
        dataList.add(new HashMap<String, String>() {{
            put("role", "user");
            put("content", txt);
        }});

        HttpURLConnection conn = null;
        BufferedReader reader = null;
        boolean messageStarted = false;
        boolean hasError = false;

        try {
            // 构造请求参数
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("model", "deepseek-chat");
            paramMap.put("messages", dataList);
            paramMap.put("stream", true);
            paramMap.put("temperature", 0.7);
            paramMap.put("max_tokens", 1000);
            paramMap.put("presence_penalty", 0);
            paramMap.put("frequency_penalty", 0);

            // 创建URL连接
            URL url = new URL(chatEndpoint);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "Bearer " + apiKey);
            conn.setRequestProperty("Accept", "text/event-stream");
            conn.setDoOutput(true);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(30000);

            // 发送请求数据
            String jsonInputString = JSON.toJSONString(paramMap);
            conn.getOutputStream().write(jsonInputString.getBytes(StandardCharsets.UTF_8));

            // 检查响应码
            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                hasError = true;
                String errorMessage = handleErrorResponse(conn, responseCode);
                callback.accept(errorMessage);
                dataList.remove(dataList.size() - 1);
                return;
            }

            // 读取流式响应
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder responseContent = new StringBuilder();
            String line;

            callback.accept("正在思考...");

            while ((line = reader.readLine()) != null) {
                if (line.startsWith("data: ")) {
                    String data = line.substring(6);
                    if ("[DONE]".equals(data)) {
                        callback.accept("[DONE]");
                        break;
                    }
                    try {
                        JSONObject jsonResponse = JSON.parseObject(data);
                        JSONArray choices = jsonResponse.getJSONArray("choices");
                        if (choices != null && !choices.isEmpty()) {
                            JSONObject choice = choices.getJSONObject(0);
                            JSONObject delta = choice.getJSONObject("delta");
                            if (delta != null && delta.containsKey("content")) {
                                String content = delta.getString("content");
                                if (!messageStarted) {
                                    callback.accept("\b\b\b\b\b\b\b"); // 清除"正在思考..."
                                    messageStarted = true;
                                }
                                responseContent.append(content);
                                callback.accept(content);
                            }
                        }
                    } catch (Exception e) {
                        System.err.println("解析响应数据失败：" + e.getMessage());
                        hasError = true;
                    }
                }
            }

            // 将完整响应添加到对话历史
            String finalResponse = responseContent.toString();
            if (!finalResponse.isEmpty()) {
                dataList.add(new HashMap<String, String>() {{
                    put("role", "assistant");
                    put("content", finalResponse);
                }});
            } else if (!hasError) {
                dataList.remove(dataList.size() - 1);
            }

        } catch (Exception e) {
            System.err.println("发生错误：" + e.getMessage());
            e.printStackTrace();
            hasError = true;
            callback.accept("服务器处理请求时发生错误，请稍后重试");
            dataList.remove(dataList.size() - 1);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String handleErrorResponse(HttpURLConnection conn, int responseCode) {
        if (responseCode == 401) {
            return "API认证失败：请检查API密钥是否正确";
        } else if (responseCode == 402) {
            return "API调用失败：账户余额不足，请联系管理员";
        } else {
            String errorMessage = "";
            try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()))) {
                String line;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                errorMessage = sb.toString();
            } catch (Exception e) {
                errorMessage = "未知错误";
            }
            System.out.println("Error response: " + errorMessage);
            return "API调用失败：" + errorMessage;
        }
    }



//    public String chat(String txt) {
//        // 检查是否连续发送用户消息
//        if (!dataList.isEmpty()) {
//            Map<String, String> lastMessage = dataList.get(dataList.size() - 1);
//            if ("user".equals(lastMessage.get("role"))) {
//                throw new IllegalStateException("Cannot add successive user messages. Please wait for the assistant's response.");
//            }
//        }
//        //添加用户消息
//        dataList.add(new HashMap<String, String>() {{
//            put("role", "user");
//            put("content", txt);
//        }});
//        // 构造请求参数
//        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("model", "deepseek-chat");
//        paramMap.put("messages", dataList);
//        try {
//            // 发送 HTTP 请求
//            String body = HttpRequest.post(chatEndpoint)
//                    .header("Authorization", "Bearer " + apiKey)
//                    .header("Content-Type", "application/json")
//                    .body(JSON.toJSONString(paramMap))
//                    .execute()
//                    .body();
//            // 解析 API 响应
//            JSONObject jsonObject = JSON.parseObject(body);
//            if (jsonObject.containsKey("error")) {
//                throw new IllegalStateException(jsonObject.getJSONObject("error").getString("message"));
//            }
//            // 提取 AI 回复并格式化
//            JSONArray choices = jsonObject.getJSONArray("choices");
//            JSONObject firstChoice = choices.getJSONObject(0);
//            JSONObject message = firstChoice.getJSONObject("message");
//            String res = message.getString("content");
//            // 格式化返回结果
//            JSONObject response = new JSONObject();
//            response.put("code", 200);
//            response.put("message", "success");
//            response.put("data", res);
//            // 将 AI 回复添加到对话历史
//            dataList.add(new HashMap<String, String>() {{
//                put("role", "assistant");
//                put("content", res);
//            }});
//            //打印到控制台
//            System.out.println(response);
//            System.out.println(dataList);
//            System.out.println(response.getJSONObject("data"));
//            System.out.println(remoteChatbo.findDoctorByDisease(1));
//            System.out.println(remoteChatbo.findByIdDisease(1));
//            return response.toJSONString();
//        } catch (Exception e) {
//            // 错误处理
//            JSONObject errorResponse = new JSONObject();
//            errorResponse.put("code", 500);
//            errorResponse.put("message", "API 调用失败: " + e.getMessage());
//            errorResponse.put("data", null);
//            return errorResponse.toJSONString();
//        }
//    }



    // 远程调用
//    public String chat(String txt) {
//        // 检查是否连续发送用户消息
//        if (!dataList.isEmpty()) {
//            Map<String, String> lastMessage = dataList.get(dataList.size() - 1);
//            if ("user".equals(lastMessage.get("role"))) {
//                throw new IllegalStateException("Cannot add successive user messages. Please wait for the assistant's response.");
//            }
//        }
//        // 添加用户消息
//        dataList.add(new HashMap<String, String>() {{
//            put("role", "user");
//            put("content", txt);
//        }});
//
//        // 检查用户消息是否包含特定命令
//        if (txt.contains("findDoctorByDisease")) {
//            // 调用远程服务查找医生
//            String doctorInfo = String.valueOf(remoteChatbo.findDoctorByDisease(1));
//            JSONObject response = new JSONObject();
//            response.put("code", 200);
//            response.put("message", "success");
//            response.put("data", doctorInfo);
//            return response.toJSONString();
//        } else if (txt.contains("findByIdDisease")) {
//            // 调用远程服务查找疾病
//            String diseaseInfo = remoteChatbo.findByIdDisease(1).toString();
//            JSONObject response = new JSONObject();
//            response.put("code", 200);
//            response.put("message", "success");
//            response.put("data", diseaseInfo);
//            return response.toJSONString();
//        } else {
//            // 构造请求参数
//            Map<String, Object> paramMap = new HashMap<>();
//            paramMap.put("model", "deepseek-chat");
//            paramMap.put("messages", dataList);
//            try {
//                // 发送 HTTP 请求
//                String body = HttpRequest.post(chatEndpoint)
//                        .header("Authorization", "Bearer " + apiKey)
//                        .header("Content-Type", "application/json")
//                        .body(JSON.toJSONString(paramMap))
//                        .execute()
//                        .body();
//                // 解析 API 响应
//                JSONObject jsonObject = JSON.parseObject(body);
//                if (jsonObject.containsKey("error")) {
//                    throw new IllegalStateException(jsonObject.getJSONObject("error").getString("message"));
//                }
//                // 提取 AI 回复并格式化
//                JSONArray choices = jsonObject.getJSONArray("choices");
//                JSONObject firstChoice = choices.getJSONObject(0);
//                JSONObject message = firstChoice.getJSONObject("message");
//                String res = message.getString("content");
//                // 格式化返回结果
//                JSONObject response = new JSONObject();
//                response.put("code", 200);
//                response.put("message", "success");
//                response.put("data", res);
//                // 将 AI 回复添加到对话历史
//                dataList.add(new HashMap<String, String>() {{
//                    put("role", "assistant");
//                    put("content", res);
//                }});
//                // 打印到控制台
//                System.out.println(response);
//                System.out.println(dataList);
//                System.out.println(response.getJSONObject("data"));
//                return response.toJSONString();
//            } catch (Exception e) {
//                // 错误处理
//                JSONObject errorResponse = new JSONObject();
//                errorResponse.put("code", 500);
//                errorResponse.put("message", "API 调用失败: " + e.getMessage());
//                errorResponse.put("data", null);
//                return errorResponse.toJSONString();
//            }
//        }
//    }
}


